package com.itstudio.myforumsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itstudio.myforumsystem.common.Result;
import com.itstudio.myforumsystem.entity.Comment;
import com.itstudio.myforumsystem.service.CommentService;
import com.itstudio.myforumsystem.utils.TokenUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    //新增或者更新评论
    @PostMapping
    public Result save(@RequestBody Comment comment){
        //
        if (comment.getId() == null){
            comment.setUserId(TokenUtils.getCurrentUser().getId());
            comment.setTime(String.valueOf(LocalDateTime.now()));
            //判断是否有主评论
            if (comment.getPid()!=null){
                Integer pid = comment.getPid();
                Comment pComment=commentService.getById(pid);
                if (pComment.getOriginId()!=null){
                    comment.setOriginId(pComment.getOriginId());
                }else {
                    comment.setOriginId(pid);
                }
            }
        }
       commentService.saveOrUpdate(comment);
        return Result.success();

    }


    //删除评论
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        commentService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        commentService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(commentService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id){
        return Result.success(commentService.getById(id));
    }



    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize){
        QueryWrapper<Comment> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(commentService.page(new Page<>(pageNum,pageSize),queryWrapper));
    }

    @GetMapping("/tree/{articleId}")
    public Result findTree(@PathVariable Integer articleId){
        //查询所有的评论和回复数量
        List<Comment> articleComments=commentService.findCommentDetail(articleId);
        //查询评论数量
        List<Comment> originList = articleComments.stream().filter(comment -> comment.getOriginId() == null).collect(Collectors.toList());

        //设置评论数据的子节点，也就是回复内容
        for (Comment origin:originList){
            // 表示回复对象集合
            List<Comment> collect = articleComments
                    .stream()
                    .filter(comment -> origin.getId().equals(comment.getOriginId()))
                    .collect(Collectors.toList());
            // 找到当前评论的父级
            collect.forEach(comment -> {
                Optional<Comment> pComment=articleComments
                        .stream()
                        .filter(c->c.getId()
                                .equals(comment.getPid()))
                        .findFirst();
                // 找到父级评论的用户id和用户昵称，并设置给当前的回复对象
                pComment.ifPresent((v ->{
                  comment.setPUserId(v.getUserId());
                  comment.setPNickname(v.getNickname());
                }));

            });
            origin.setChildren(collect);


        }

        return Result.success(originList);
    }


}
